// ==========================================================================
// GFast自动生成logic操作代码。
// 生成日期：2024-11-11 20:33:48
// 生成路径: internal/app/system/logic/addresses.go
// 生成人：王中阳
// desc:收货地址
// company:云南奇讯科技有限公司
// ==========================================================================

package addresses

import (
	"context"
	"errors"

	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/util/gconv"
	"github.com/tiger1103/gfast/v3/internal/app/system/consts"
	"github.com/tiger1103/gfast/v3/internal/app/system/dao"
	"github.com/tiger1103/gfast/v3/internal/app/system/model"
	"github.com/tiger1103/gfast/v3/internal/app/system/model/do"
	"github.com/tiger1103/gfast/v3/internal/app/system/service"
	"github.com/tiger1103/gfast/v3/library/liberr"
	"github.com/xuri/excelize/v2"
)

func init() {
	service.RegisterAddresses(New())
}

func New() service.IAddresses {
	return &sAddresses{}
}

type sAddresses struct{}

func (s *sAddresses) List(ctx context.Context, req *model.AddressesSearchReq) (listRes *model.AddressesSearchRes, err error) {
	listRes = new(model.AddressesSearchRes)
	err = g.Try(ctx, func(ctx context.Context) {
		m := dao.Addresses.Ctx(ctx).WithAll()
		if req.Id != "" {
			m = m.Where(dao.Addresses.Columns().Id+" = ?", req.Id)
		}
		if req.Userid != "" {
			m = m.Where(dao.Addresses.Columns().Userid+" = ?", gconv.Int(req.Userid))
		}
		if req.Name != "" {
			m = m.Where(dao.Addresses.Columns().Name+" like ?", "%"+req.Name+"%")
		}
		if req.Phone != "" {
			m = m.Where(dao.Addresses.Columns().Phone+" = ?", req.Phone)
		}
		if req.SchoolId != "" {
			m = m.Where(dao.Addresses.Columns().SchoolId+" = ?", gconv.Int(req.SchoolId))
		}
		if req.Addr != "" {
			m = m.Where(dao.Addresses.Columns().Addr+" = ?", req.Addr)
		}
		if req.Detail != "" {
			m = m.Where(dao.Addresses.Columns().Detail+" = ?", req.Detail)
		}
		if req.AddrName != "" {
			m = m.Where(dao.Addresses.Columns().AddrName+" like ?", "%"+req.AddrName+"%")
		}
		if req.Lat != "" {
			m = m.Where(dao.Addresses.Columns().Lat+" = ?", req.Lat)
		}
		if req.Lng != "" {
			m = m.Where(dao.Addresses.Columns().Lng+" = ?", req.Lng)
		}
		if req.IsDel != "" {
			m = m.Where(dao.Addresses.Columns().IsDel+" = ?", gconv.Int(req.IsDel))
		}
		if req.IsDefault != "" {
			m = m.Where(dao.Addresses.Columns().IsDefault+" = ?", gconv.Int(req.IsDefault))
		}
		if len(req.DateRange) != 0 {
			m = m.Where(dao.Addresses.Columns().CreatedAt+" >=? AND "+dao.Addresses.Columns().CreatedAt+" <=?", req.DateRange[0], req.DateRange[1])
		}
		listRes.Total, err = m.Count()
		liberr.ErrIsNil(ctx, err, "获取总行数失败")
		if req.PageNum == 0 {
			req.PageNum = 1
		}
		listRes.CurrentPage = req.PageNum
		if req.PageSize == 0 {
			req.PageSize = consts.PageSize
		}
		order := "id desc"
		if req.OrderBy != "" {
			order = req.OrderBy
		}
		var res []*model.AddressesListRes
		err = m.Page(req.PageNum, req.PageSize).Order(order).Scan(&res)
		liberr.ErrIsNil(ctx, err, "获取数据失败")
		listRes.List = make([]*model.AddressesListRes, len(res))
		for k, v := range res {
			listRes.List[k] = &model.AddressesListRes{
				Id:             v.Id,
				Userid:         v.Userid,
				LinkedUserid:   v.LinkedUserid,
				Name:           v.Name,
				Phone:          v.Phone,
				SchoolId:       v.SchoolId,
				LinkedSchoolId: v.LinkedSchoolId,
				Addr:           v.Addr,
				Detail:         v.Detail,
				AddrName:       v.AddrName,
				Lat:            v.Lat,
				Lng:            v.Lng,
				IsDel:          v.IsDel,
				IsDefault:      v.IsDefault,
				CreatedAt:      v.CreatedAt,
			}
		}
	})
	return
}

func (s *sAddresses) GetExportData(ctx context.Context, req *model.AddressesSearchReq) (listRes []*model.AddressesInfoRes, err error) {
	err = g.Try(ctx, func(ctx context.Context) {
		m := dao.Addresses.Ctx(ctx).WithAll()
		if req.Id != "" {
			m = m.Where(dao.Addresses.Columns().Id+" = ?", req.Id)
		}
		if req.Userid != "" {
			m = m.Where(dao.Addresses.Columns().Userid+" = ?", gconv.Int(req.Userid))
		}
		if req.Name != "" {
			m = m.Where(dao.Addresses.Columns().Name+" like ?", "%"+req.Name+"%")
		}
		if req.Phone != "" {
			m = m.Where(dao.Addresses.Columns().Phone+" = ?", req.Phone)
		}
		if req.SchoolId != "" {
			m = m.Where(dao.Addresses.Columns().SchoolId+" = ?", gconv.Int(req.SchoolId))
		}
		if req.Addr != "" {
			m = m.Where(dao.Addresses.Columns().Addr+" = ?", req.Addr)
		}
		if req.Detail != "" {
			m = m.Where(dao.Addresses.Columns().Detail+" = ?", req.Detail)
		}
		if req.AddrName != "" {
			m = m.Where(dao.Addresses.Columns().AddrName+" like ?", "%"+req.AddrName+"%")
		}
		if req.Lat != "" {
			m = m.Where(dao.Addresses.Columns().Lat+" = ?", req.Lat)
		}
		if req.Lng != "" {
			m = m.Where(dao.Addresses.Columns().Lng+" = ?", req.Lng)
		}
		if req.IsDel != "" {
			m = m.Where(dao.Addresses.Columns().IsDel+" = ?", gconv.Int(req.IsDel))
		}
		if req.IsDefault != "" {
			m = m.Where(dao.Addresses.Columns().IsDefault+" = ?", gconv.Int(req.IsDefault))
		}
		if len(req.DateRange) != 0 {
			m = m.Where(dao.Addresses.Columns().CreatedAt+" >=? AND "+dao.Addresses.Columns().CreatedAt+" <=?", req.DateRange[0], req.DateRange[1])
		}
		if req.PageNum == 0 {
			req.PageNum = 1
		}
		if req.PageSize == 0 {
			req.PageSize = consts.PageSize
		}
		order := "id desc"
		if req.OrderBy != "" {
			order = req.OrderBy
		}
		err = m.Page(req.PageNum, req.PageSize).Order(order).Scan(&listRes)
		liberr.ErrIsNil(ctx, err, "获取数据失败")
	})
	return
}

func (s *sAddresses) Import(ctx context.Context, file *ghttp.UploadFile) (err error) {
	if file == nil {
		err = errors.New("请上传数据文件")
		return
	}
	var data []do.Addresses
	err = g.Try(ctx, func(ctx context.Context) {
		f, err := file.Open()
		liberr.ErrIsNil(ctx, err)
		defer f.Close()
		exFile, err := excelize.OpenReader(f)
		liberr.ErrIsNil(ctx, err)
		defer exFile.Close()
		rows, err := exFile.GetRows("Sheet1")
		liberr.ErrIsNil(ctx, err)
		if len(rows) == 0 {
			liberr.ErrIsNil(ctx, errors.New("表格内容不能为空"))
		}
		d := make([]interface{}, len(rows[0]))
		data = make([]do.Addresses, len(rows)-1)
		for k, v := range rows {
			if k == 0 {
				continue
			}
			for kv, vv := range v {
				d[kv] = vv
			}
			data[k-1] = do.Addresses{
				Userid:    gconv.Int64(d[0]),
				Name:      d[1],
				Phone:     d[2],
				SchoolId:  gconv.Int64(d[3]),
				Addr:      d[4],
				Detail:    d[5],
				AddrName:  d[6],
				Lat:       d[7],
				Lng:       d[8],
				IsDel:     gconv.Int64(d[9]),
				IsDefault: gconv.Int64(d[10]),
				CreatedAt: gconv.GTime(d[11]),
				UpdatedAt: gconv.GTime(d[12]),
			}
		}
		if len(data) > 0 {
			err = g.DB().Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {
				_, err = dao.Addresses.Ctx(ctx).Batch(500).Insert(data)
				return err
			})
			liberr.ErrIsNil(ctx, err)
		}
	})
	return
}

// LinkedDataSearch 相关连表查询数据
func (s *sAddresses) LinkedAddressesDataSearch(ctx context.Context) (res *model.LinkedAddressesDataSearchRes, err error) {
	res = new(model.LinkedAddressesDataSearchRes)
	res.LinkedAddressesUsers, err = s.ListAddressesUsers(ctx)
	liberr.ErrIsNil(ctx, err, "获取关联表信息失败")
	res.LinkedAddressesSchools, err = s.ListAddressesSchools(ctx)
	liberr.ErrIsNil(ctx, err, "获取关联表信息失败")
	return
}

func (s *sAddresses) GetById(ctx context.Context, id int) (res *model.AddressesInfoRes, err error) {
	err = g.Try(ctx, func(ctx context.Context) {
		err = dao.Addresses.Ctx(ctx).WithAll().Where(dao.Addresses.Columns().Id, id).Scan(&res)
		liberr.ErrIsNil(ctx, err, "获取信息失败")
	})
	return
}

func (s *sAddresses) Add(ctx context.Context, req *model.AddressesAddReq) (err error) {
	err = g.Try(ctx, func(ctx context.Context) {
		_, err = dao.Addresses.Ctx(ctx).Insert(do.Addresses{
			Userid:    req.Userid,
			Name:      req.Name,
			Phone:     req.Phone,
			SchoolId:  req.SchoolId,
			Addr:      req.Addr,
			Detail:    req.Detail,
			AddrName:  req.AddrName,
			Lat:       req.Lat,
			Lng:       req.Lng,
			IsDel:     req.IsDel,
			IsDefault: req.IsDefault,
		})
		liberr.ErrIsNil(ctx, err, "添加失败")
	})
	return
}

func (s *sAddresses) Edit(ctx context.Context, req *model.AddressesEditReq) (err error) {
	err = g.Try(ctx, func(ctx context.Context) {
		_, err = dao.Addresses.Ctx(ctx).WherePri(req.Id).Update(do.Addresses{
			Userid:    req.Userid,
			Name:      req.Name,
			Phone:     req.Phone,
			SchoolId:  req.SchoolId,
			Addr:      req.Addr,
			Detail:    req.Detail,
			AddrName:  req.AddrName,
			Lat:       req.Lat,
			Lng:       req.Lng,
			IsDel:     req.IsDel,
			IsDefault: req.IsDefault,
		})
		liberr.ErrIsNil(ctx, err, "修改失败")
	})
	return
}

func (s *sAddresses) Delete(ctx context.Context, ids []int) (err error) {
	err = g.Try(ctx, func(ctx context.Context) {
		_, err = dao.Addresses.Ctx(ctx).Delete(dao.Addresses.Columns().Id+" in (?)", ids)
		liberr.ErrIsNil(ctx, err, "删除失败")
	})
	return
}

func (s *sAddresses) ListAddressesUsers(ctx context.Context) (linkedAddressesUsers []*model.LinkedAddressesUsers, err error) {
	err = g.Try(ctx, func(ctx context.Context) {
		err = dao.Users.
			Ctx(ctx).
			Fields(model.LinkedAddressesUsers{}).Scan(&linkedAddressesUsers)
		liberr.ErrIsNil(ctx, err)
	})
	return
}

func (s *sAddresses) ListAddressesSchools(ctx context.Context) (linkedAddressesSchools []*model.LinkedAddressesSchools, err error) {
	err = g.Try(ctx, func(ctx context.Context) {
		err = dao.Schools.
			Ctx(ctx).
			Fields(model.LinkedAddressesSchools{}).Scan(&linkedAddressesSchools)
		liberr.ErrIsNil(ctx, err)
	})
	return
}
